package handler

import (
	"context"
	"go.uber.org/zap"
	"user_srv/global"
	"user_srv/model"

	proto "user_srv/proto"
)

type User_srv struct{}

func (h *User_srv) AddUser(ctx context.Context, req *proto.ResponseUserInfo, rep *proto.Response) error {
	user := &model.User{}

	if err := global.SwapTo(req, user); err != nil {
		return err
	}
	zap.S().Debug("入参", req)
	if global.DB.Where(&model.User{Account: req.Account}).First(&user).RowsAffected == 1 {
		zap.S().Debug("根据账户信息查询到用户信息")
		rep.Msg = "账户已存在"
		return nil
	}
	if global.DB.Where(&model.User{Mobile: req.Mobile}).First(&user).RowsAffected == 1 {
		zap.S().Debug("根据手机号账户信息查询到用户信息")
		rep.Msg = "手机号已存在"
		return nil
	}

	result := global.DB.Create(&user)
	if result.Error != nil {
		rep.Msg = "创建失败"
		return nil

	}
	//
	////赋值
	//user.Account = req.Account
	//user.Password = req.PassWord
	//user.UserName = req.UserName
	//user.Departments = req.Departments
	//user.Mobile = req.Mobile
	//user.Role = req.Role
	//user.Addr = req.Addr
	//user.Email = req.Email
	//user.Password = req.PassWord
	//result := global.DB.Create(&user)
	//
	//if result.Error != nil {
	//	rep.Msg = "创建失败"
	//}

	return nil
}

// GetUserInfoByUserid 根据id查询用户信息
func (h *User_srv) GetUserInfoByUserid(ctx context.Context, req *proto.RequestUserId, rep *proto.ResponseUserInfo) error {
	var user model.User
	result := global.DB.First(&user, req.Userid)
	if result.RowsAffected == 0 {
		zap.S().Debug("[UpdateUser] 用户不存在")
		return nil
	}
	rep = UserForResponse(user)
	return nil
}

func (h *User_srv) GetUserInfoByAccount(ctx context.Context, req *proto.RequestAccount, rep *proto.ResponseUserInfo) error {
	return nil
}

func (h *User_srv) GetUserInfoByName(ctx context.Context, req *proto.RequestName, rep *proto.ResponseUserInfo) error {
	return nil
}

func (h *User_srv) GetUserInfoByMobile(ctx context.Context, req *proto.RequestMobile, rep *proto.ResponseUserInfo) error {
	return nil
}

// UserForResponse 类型转化
func UserForResponse(user model.User) *proto.ResponseUserInfo {
	response := &proto.ResponseUserInfo{
		Id:          int64(user.ID),
		Account:     user.Account,
		UserName:    user.UserName,
		PassWord:    user.Password,
		Departments: user.Departments,
		Email:       user.Email,
		Status:      user.Status,
		Role:        user.Role,
		Addr:        user.Addr,
		Mobile:      user.Mobile,
	}
	return response
}
